<?php
/**
 * Created by PhpStorm.
 * User: 盛茂国
 * Tel: 18394333958
 * Date: 2020/6/2
 * Time: 10:31
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use GuzzleHttp\RetryMiddleware;
use hillpy\MiniProgramSDK\MiniProgram;
use think\Db;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','miniauth','getXcxuser','bind','minilogin','collect','finance'];
    protected $noNeedRight = '*';
    protected $miniProgram;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
//    public function third()
//    {
//        $url = url('user/index');
//        $platform = $this->request->request("platform");
//        $code = $this->request->request("code");
//        $config = get_addon_config('third');
//        if (!$config || !isset($config[$platform])) {
//            $this->error(__('Invalid parameters'));
//        }
//        $app = new \addons\third\library\Application($config);
//        //通过code换access_token和绑定会员
//        $result = $app->{$platform}->getUserInfo(['code' => $code]);
//        if ($result) {
//            $loginret = \addons\third\library\Service::connect($platform, $result);
//            if ($loginret) {
//                $data = [
//                    'userinfo'  => $this->auth->getUserinfo(),
//                    'thirdinfo' => $result
//                ];
//                $this->success(__('Logged in successful'), $data);
//            }
//        }
//        $this->error(__('Operation failed'), $url);
//    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    public function miniauth(Request $request){

        $code=$request->param('code');
        $popenid=$request->param('popenid');
        //1.捕获code
        //2.代发curl请求到微信登录校验地址
        //3.处理返回session_key+openid
        //4.自定义登录状态
        //5.把用户信息解密，保存到数据库
        //6.返回token 给前端
        //7.前端保存登录状态
        $appId="wxa20431ee4c6128e2";
        $appSecret="befc91bb4c556b12a62e9caa4005555a";
        $accessToken=session('miniprogram_access_token_appid_' . $appId);
        $miniProgram=new MiniProgram($appId,$appSecret,$accessToken);

        $opendData=$miniProgram->jscode2Session($code);
        $this->miniProgram=$miniProgram;
        //print_r($opendData);die;
        if(!$accessToken){
            isset( $miniProgram->accessTokenData['access_token'] ) && $accessToken=$miniProgram->accessTokenData['access_token'];
            if($accessToken){
                if (isset($miniProgram->accessTokenData['expires_in'])){
                    $cacheTime=$miniProgram->accessTokenData['expires_in']-30;
                }else{
                    $cacheTime=0;
                }
                session('miniprogram_access_token_appid_' . $appId, $cacheTime, $accessToken);
            }
        }

        $res=[
            'code'=>200,
            'msg'=>'登录成功',
            'data'=>[
                'token'=>$accessToken,
                'opendData'=>$opendData
            ]
        ];
        return json_encode($res);
    }
    public function getXcxuser(Request $request){
        $openid=$request->param('openid');

        $popenid=$request->param('popenid');
        ///echo $popenid;
       // file_put_contents('debug.txt',$popenid);
        $rawData=$request->param('rawData');
        $session_key=$request->param('session_key');
        $json=html_entity_decode($rawData);
        $rawDataArr=json_decode($json,true);
        $isMember=db('user')->where('open_id',$openid)->find();//查询是不是会员

        $data=[
            'open_id'=>$openid,//$request->param('openid'),
            'avatar'=>$rawDataArr['avatarUrl'],//$request->param('avatar'),
            'nickname'=>$rawDataArr['nickName'],//$request->param('nickname'),
            'gender'=>$rawDataArr['gender'],//$request->param('gender'),
            'city'=>$rawDataArr['city'],//$request->param('city'),
            'province'=>$rawDataArr['province'],//$request->param('province'),
            'session_key'=>$session_key,//$request->param('session_key'),
            'createtime'=>time(),
            'group_id'=>2
        ];

        if(!$isMember){//不是会员
            $db=db('user');
            if ($popenid=='undefied' || empty($popenid)){ //如果没有老子ID
                $isSave=$db->data($data)->insert();
                if($isSave){
                    return json(['status'=>200,'msg'=>'成功获取授权','data'=>$data]);
                }else{
                    return json(['status'=>400,'用户数据存储失败']);
                }
            }else{//如果有老子ID
                //0.给儿子绑定老子id
                $user=$db->where('open_id','=',$popenid)->find();   //查询老子信息
                $data['parent']=$user['id'];
                //判断老子被分享几次
                if($user['sharenum']>=2){//如果老子被分享3次，那么重置计数器为0
                    //4.更新老子猫币数量
                    $db->where('open_id','=',$popenid)->setField('catcoin',$user['catcoin']+1);//给老子加猫币
                    $db->where('open_id','=',$popenid)->setField('sharenum',0);//重置计数器
                    //写猫币的流水日志
                    db('usercatcoinlog')->data([
                        'catcoin'=>1,
                        'createtime'=>time(),
                        'remark'=>'分享小程序，奖励猫币',
                        'uid'=>$user['id']
                    ])->insert();
                }else{//计步器+1
                    $db->where('open_id','=',$popenid)->setInc('sharenum',1);
                }
            }
            //注册当前用户
            $isSave=$db->data($data)->insert();
            if($isSave){
                return json(['status'=>200,'msg'=>'成功获取授权','data'=>$data]);
            }else{
                return json(['status'=>400,'用户数据存储失败']);
            }
        }else{//是会员直接返回会员信息
            $data=[
                'open_id'=>$isMember['open_id'],
                'avatar'=>$isMember['avatar'],
                'nickname'=>$isMember['nickname'],
                'gender'=>$isMember['gender'],
                'city'=>$isMember['city'],
                'province'=>$isMember['province'],
                'session_key'=>$isMember['session_key'],
                'group_id'=>2
            ];
            return json(['status'=>200,'msg'=>'您已经是游客组成员,请绑定手机号，升级普通用户','data'=>$data]);
        }
    }

    //绑定手机号码
    public function bind(Request $request){
        if (!$request->isPost()){
            return ;
        }else{
            $openid=$request->param('openid');
            $mobile=$request->param('mobile');
            $code=$request->param('code');
            $password=$request->param('password');
            $repassword=$request->param('repassword');

            if(!preg_match('/^1[3,5,7,8,9]\d{9}/',$mobile)){
                return json(['code'=>400,'msg'=>'电话号码非法']);
            }

            if($password!==$repassword){
                return json(['code'=>400,'msg'=>'密码和确认密码不一致']);
            }

            if(empty($password) || empty($repassword) || empty($code) || empty($code) || empty($openid)){
                return json(['code'=>400,'msg'=>'有必填字段为空']);
            }



            $sms=db('sms')->where('mobile',$mobile)->order('id desc')->find();
            $issend= $sms['code']===$code ? true : false;
            //print_r($sms);die;
            if($issend){
                $auth=new Auth();
                $db=db('user');
                $salt=Random::alnum();
                $data=[
                    'mobile'=>$mobile,
                    'group_id'=>1,
                    'open_id'=>$openid,
                    'password'=>$auth->getEncryptPassword($password,$salt),
                    'salt'=>$salt
                ];
                $isauth=$db->where('open_id',$openid)->find();
                if(!$isauth){
                    return json(['code'=>400,'msg'=>'您未授权小程序获取openid']);
                }else{
                    $isSave=$db->where('open_id',$openid)->data($data)->update();
                    if($isSave){
                        return json(['code'=>200,'msg'=>'注册成功，您已经是普通会员，请完成一次充值，升级为付费用户']);
                    }else{
                        return json(['code'=>400,'msg'=>'注册失败']);
                    }
                }
            }else{
                return json(['code'=>400,'msg'=>'你提交的手机和短信验证码非法']);
            }

        }
    }

    public function minilogin(Request $request){

        $mobile=$request->param('mobile');
        $password=$request->param('password');
        if(!$request->isPost()) return;
        $user=db('user')->where('mobile',$mobile)->find();
        $auth=new \app\common\library\Auth();
        //echo $auth->getEncryptPassword($password,$user['salt']);die;

        if($user['password']===$auth->getEncryptPassword($password,$user['salt'])){
            $data['loginip']=$request->ip;
            $data['logintime']=time();
            $data['id']=$user['id'];
            db('user')->data($data)->update();
            return json(['code'=>200,'msg'=>'登录成功','data'=>$user]);
        }else{
            return json(['code'=>400,'msg'=>'账号或密码错误']);
        }
    }
    public function collect(Request $request){
        $pageNum=($request->param('pageNum')) ? $request->param('pageNum') : 5;
        $page=($request->param('page')) ? $request->param('page','intval') :0;

        $openid=$request->param('openid');
        $uid=db('user')->where('open_id','=',$openid)->value('id');
        $workerids=db('workercollect')->where('uid','=',$uid)->where('status','=',1)->column('workerid');

        $wids=implode(',',$workerids);

        $list=db('worker')->where('workerid','in',$wids)->page($page,$pageNum)->select();

        foreach ($list as $key=>$value){
            $list[$key]['image']=$request->domain().$value['image'];
        }

        $data['total']=db('worker')->count();
        $data['page']=$page;
        $data['pageNum']=$pageNum;
        $data['data']=$list;
        return json(['status'=>200,'msg'=>'获取作品列表成功','data'=>$data]);
    }
    //用户余额和猫币接口
    public function finance(Request $request){
        $openid=$request->param('openid');
        $finace=db('user')->where('open_id','=',$openid)->field('id,money,catcoin,totalcatcoin')->find();
        //print_r($finace);
        if($finace){
            return json(['status'=>200,'msg'=>'获取成功','data'=>$finace]);
        }else{
            return json(['status'=>400,'msg'=>'没有数据,或参数错误']);
        }
    }
}
